<?php


namespace App\Http\Swoole;


use SwooleTW\Http\Websocket\Parser;
use SwooleTW\Http\Websocket\SocketIO\Packet;

class SocketParser extends Parser
{

    public function encode(string $event, $data)
    {
        /*
        $packet = Packet::MESSAGE . Packet::EVENT;
        $shouldEncode = is_array($data) || is_object($data);
        $data = $shouldEncode ? json_encode($data) : $data;
        $format = $shouldEncode ? '["%s",%s]' : '["%s","%s"]';

        return $packet . sprintf($format, $event, $data);
        */
        $string = ['event' => $event, 'data' => $data];
        return json_encode($string);

    }

    public function decode($frame)
    {
        $data = json_decode($frame->data, true);
        if (!$data || !isset($data['event'])) {
            return ['event' => 'error', 'data' => $frame->data,'fd'=>$frame->fd];
        }
        return ['event' => $data['event'], 'data' => $data['data'] ?? '','fd'=>$frame->fd];
    }
}